const webSocket = require('ws');
const webSocketServer = webSocket.Server;
const wss = new webSocketServer({
    port:9090
});
let socketId=0;
function broadcast(data) {
    wss.clients.forEach(function (client) {
        console.log('send'+data);
        client.send(data);
    })
}
wss.on("connection",ws=>{
    console.log('in websocket');
    ws.user="";
    ws.on("message",message=>{
        console.log('this is previous user'+ws.user);
        console.log(message);
        let result = JSON.parse(message);
        if(result.type==='user'){
            console.log('this type is user');
            ws.user=result.user;
            socketId++;
            let msg = JSON.stringify({
                type:'user',
                userID:socketId,
                lenght:wss.clients.size
            });
            ws.send(msg);
            if(ws.user){
                let msg = JSON.stringify({
                    type:'room_in',
                    user:ws.user,
                });
                broadcast(msg);
            }
        }
        if(result.type==='msg'){
            if(result.msg&&result.msg.trim()){
                let msg = JSON.stringify({
                    type:'msg',
                    user:ws.user,
                    msg:result.msg.trim()
                });
                broadcast(msg);
            }
        }
    });
    ws.on("close",()=>{
        let length = wss.clients.size;
        let msg = JSON.stringify({
            type:'info_out',
            user:ws.user,
            length:length
        });
        broadcast(msg);
    })
});
